package com.csap.framework.oauth2.security;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.exception.NotLoginException;
import com.csap.framework.extension.result.ResultParam;
import com.csap.framework.extension.result.ResultUtil;
import com.csap.framework.oauth2.exception.Oauth2Exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @Author ycf
 * @Date 2021/8/23 9:38 下午
 * @Version 1.0
 */
@ControllerAdvice
@Slf4j
public class SecurityExceptionHandler {

    /**
     * 内部自定义异常错误
     *
     * @param e 异常
     * @return 结果
     */
    @ExceptionHandler({NotLoginException.class})
    public ResponseEntity<ResultParam<?>> handlerSellerException(NotLoginException e) {
        log.error("NotLoginException:{},loginType:{},type:{}", e.getMessage(), e.getLoginType(), e.getType());
        return getResponse(ResultUtil.error(e.getType(), e.getMessage()), e.getHttpStatus());
    }

    /**
     * 授权认证错误
     *
     * @param e 异常
     * @return 结果
     */
    @ExceptionHandler({Oauth2Exception.class})
    public ResponseEntity<ResultParam<?>> oauth2Exception(Oauth2Exception e) {
        log.error("oauth2Exception:{},descr:{},request url:{}", e.getMessage(), e.exceptionType().getDescr(), SaHolder.getRequest().getUrl());
        return getResponse(ResultUtil.error(String.valueOf(e.exceptionType().getHttpStatus().value()), e.getMessage(), e.exceptionType().getDescr()), e.exceptionType().getHttpStatus());
    }

    /**
     * 公用响应
     *
     * @param resultParam 响应的参数
     * @param httpStatus  http状态
     * @return 结果
     */
    private ResponseEntity<ResultParam<?>> getResponse(ResultParam<?> resultParam, HttpStatus httpStatus) {
        return new ResponseEntity<>(resultParam, httpStatus);
    }
}
